package com.quick.im.server.component;

import com.quick.im.server.handler.ServerHandler;

import com.quick.im.common.util.ProtobufDecoder;
import com.quick.im.common.util.ProtobufEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
@Slf4j
public class NettyServerConfig {

    @Value("${netty.server.port}")
    private int serverPort;


    public void start() throws InterruptedException, UnknownHostException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new ProtobufDecoder())  // 解码器
                                    .addLast(new ProtobufEncoder())  // 编码器
                                    .addLast(new ServerHandler());  // 处理消息
                        }
                    });
            InetAddress localHost = InetAddress.getLocalHost();
            log.info("启动netty client success ip:{}----->port{}",localHost.getHostAddress(),serverPort);
            ChannelFuture sync = bootstrap.bind(serverPort).sync();
            sync.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
